/**
 **/
//var ajax_url = "/dbdiffrepository/json.php"; // Local host for development
// Prod var ajax_url = "http://andreasmarkussen.kodingen.com/json.php", // for production use
//Prod 
var ajax_url = "http://bildelspriser.dk/dbdiffrepository/json.php" // for production use
$.ajaxSetup({
    url: ajax_url, 
    type: "POST"
    });
    
var uniqid = null;
var logged_id_user = null



//http://www.w3schools.com/js/tryit.asp?filename=tryjs_cookie_username

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
  {
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

function saveUserIdAdUniqueId(new_username,new_uniqid){
    if(!new_username) return;
    if(!new_uniqid) return;
    logged_in_user = new_username;
    uniqid = new_uniqid;
    setCookie('username',logged_id_user,365);
    setCookie('uniqid',uniqid,365);
    user_info('Cookies saved for your convinience');
}

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

function checkCookieOrg()
{
var username=getCookie("username");
if (username!=null && username!="")
  {
  alert("Welcome again " + username);
  }
else 
  {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username,365);
    }
  }
}

function checkCookie()
{
var username=getCookie("username");
logged_id_user = user_name;
uniqid = getCookie("uniqid");
if (username!=null && username!="")
  {
  user_info("Welcome again " + username+' (The cookies saved you form logging in)');
  // do login stuff
  }
else 
  {
  //username=prompt("Please enter your name:","");
  user_info('Please login. The cookies have been eaten?');
  if (username!=null && username!="")
    {
    setCookie("username",username,365);
    }
  }
}

//RUN CHECK cookie 



function load_from_repository(div_name,ta_name,txt_key){
  key_name=$(txt_key).val();
  log_text = "Loading Snapshot ('"+key_name+"') from Repository...";    
  
  var values = extract_form_values(div_name);
  values['format']='json';
  values['FUNC']='getLoadSnapShotFromRepository';
  var handler = function(data){
//    write_log("post returned <br>");
    $(ta_name).val(data);
  };  
  $.ajax({data:values,success:handler});// End Ajax Call  
  /*$(ta_name).val(log_text);
  write_log(log_text);   
  $.post( {FUNC: "getLoadSnapShotFromRepository", SNAPSHOT_NAME: key_name},
  function(data){
//    write_log("post returned <br>");
    $(ta_name).val(data);
  }, "html");*/
}// end of load_from_repository

var ctl_structure_name = "textarea_snapshot_text";
      
function new_copy_text_to_respository(){
    write_log("NEW Clearing log before sending to Server..");
    user_info('Saving snapshot to Repository');
    var jq_textarea = $('#'+ctl_structure_name);
    //var ta = document.getElementById(ctl_structure_name);
    if(jq_textarea.length == 0){
        error("No Textarea found - nothing sent to the DbDiffRepository server");
        return;
    }
    var ta_content = jq_textarea.val();
    snapshot_name_value=$('#snapshot_name').val();  
    write_log("First part of Repository Text is '" + ta_content.slice(0,70)+"... (cropped to 70)'");      
    /*var values = {};
    values['FUNC'] = 'saveSnapshot';
    values['uniqid'] = uniqid;
    values['select_id'] = select_id;
    values['value'] = 'environment_id';
    values['text'] = 'environment_name';
    $.ajax({data:values,success:set_select_from_json});*/ 

      var values = extract_form_values('#div_save');
      values['format']='json';
      values['FUNC']='insertSnapshot';
      values['snapshot_text'] = ta_content;
      $.ajax({data:values,success:handle_generic_json_reply});// End Ajax Call  
      user_info('Snapshot is Now sent to Repository');
   return;    

    var jqxhr = $.post(
          ajax_url , {JSON_DB_LAYOUT: ta_content,SNAPSHOT_NAME: snapshot_name_value+'_old_form',format:'HTML'},
          function(data) {write_log('XmlHttpRequest POST returned:'+data);}
      )
      .done(function(text) {write_log("Sending data to the server was a success<br>/"+text.substring(0,70));})
      .fail(function(jqXHR, textStatus,x) { 
          write_log( "Request failed: " + textStatus +x);
            })
      .always(function() {write_log("Sending data to the server is complete!");});
}

function extract_form_values(element_query){
      var values = {};
      var myForm = $(element_query);
      //write_log("Element Query = "+$(element_query).text() + " contains " + myForm[0].childNodes.length + " elements ");
      $.each(myForm.children('select,input,textarea'), function(i, field) {
         values[field.name] = field.value;
         //write_log(" - Field " + field.name + ' has value ' +  field.value);
       });// end of each...
      //write_log("values are logged "+values.join());
      return values;
}      

function handle_login(json){
  write_log('handle_login - JSON: </br>'+ json.substring(0,60)+'... (croped to 60 chars)'); 
  user_info('Login reply in JSON: '+ json.substring(0,60)+'... (croped to 60 chars)');
  eval('var myObj = '+json);
  if(!(myObj && myObj.row.user_name)){
      error('Unable to login - invalid combination of username and password?');
      return;
  }
  user_info('User_name '+myObj.row.user_name+' SUCCESSFULLY logged in');
  uniqid = myObj.row.uniqid;
  logged_id_user = myObj.row;
  saveUserIdAdUniqueId(logged_id_user, uniqid);
  handle_login_with_uniqid(uniqid);
}

function handle_login_with_uniqid(uniqid){
  if($('#txt_snapshot_name1').length){
      handle_login_landing_page(uniqid);
  }else if($('#textarea_snapshot_text').length){
      //$('#textarea_snapshot_text').before("<div id='div_save' />");
      var existed = create_element_if_not_exists('#textarea_snapshot_text', 'div#div_save', "<div id='div_save' />", 'before');
      if(!existed){ // if not exist, then it is new, and should be filled      
        $('#div_save').append("<label for='snapshot_name'>Snapshot Name</label>");
        $('#div_save').append("<input type='text' id='snapshot_name' name='snapshot_name' />");
        $('#div_save').append("<input type='button' name='btnSaveToRep'  value='Save to Repository' onclick='new_copy_text_to_respository()' />");
      }//$('#snapshot_name').after("<input type='button' name='btnSaveToRep'  value='Save to Repository' onclick='new_copy_text_to_respository()' />");
      handle_login_export_page(uniqid);      
  }        
}

function handle_generic_json_reply(json_as_text){
  write_log('Generic JSON reply: </br>'+ json_as_text.substring(0,60)+'... (croped to 60 chars)'); 
  user_info('Reply from server OK: '+ json_as_text.substring(0,60)+'... (croped to 60 chars)');
  eval('var myObj = '+json_as_text);
  write_log('Generic JSON Reply :'+dump(myObj));
  var key=null;
  var latest_key = null;
  if(myObj.log){
      for(key in myObj.log){
         latest_key = key;
     }
     user_info('Info from Repository: '+myObj.log[latest_key]);
  }
  else{
      user_info('No log from server:');
  }
}

function create_element_if_not_exists(parrent_element_selector,new_element_selector,element_html,how){
    if($(new_element_selector).length==1)
        return true;
    var parrent = $(parrent_element_selector);
    if(parrent.length==0)
        error('Parent Element could not be found "'+parrent_element_selector+'" ');
    var js='parrent.'+how+'(\"'+element_html+'\")';
    eval(js);
    if($(new_element_selector).length==0)
        error('Could not create element with code "'+js+'" ');
    return false;
}


function handle_login_landing_page(uniqid){
    var env_select1 = create_or_replace_env_select(uniqid,'txt_snapshot_name1');
    var env_select2 = create_or_replace_env_select(uniqid,'txt_snapshot_name2');
    var app_select1 = create_or_replace_app_select(uniqid, 'txt_snapshot_name1');
    var app_select2 = create_or_replace_app_select(uniqid, 'txt_snapshot_name2');    
}

function handle_login_export_page(uniqid){
    var env_select1 = create_or_replace_env_select(uniqid,'snapshot_name');
    var app_select1 = create_or_replace_app_select(uniqid,'snapshot_name');
}

/**
 * @return HTMLSelectElement
 */
function create_or_replace_env_select(uniqid,container_id){
    select_id = container_id+'_select_env';
    write_log("Text field name select_id = '"+select_id+"'");
    //$('#'+container_id).after("<div id='"+container_id+"_div' />");
    var select_obj = create_or_replace_select(container_id, select_id, "Environment",'environment_id');
    if(!select_obj) return null;
    var options = select_obj.options;
    options.remove();
    options[options.length] = new Option("Loading Environments", null, false, false);
    var values = {};
    values['FUNC'] = 'getEnvironments';
    values['uniqid'] = uniqid;
    values['select_id'] = select_id;
    values['value'] = 'environment_id';
    values['text'] = 'environment_name';
    values['return_request'] = true;
    $.ajax({data:values,success:set_select_from_json});
    return select_obj;
}

/**
 * @return HTMLSelectElement
 */
function create_or_replace_app_select(uniqid,container_id){
    select_id = container_id+'_select_app';
    write_log("Text field name select_id= '"+select_id+"'");
    var select_obj = create_or_replace_select(container_id, select_id, "Application",'application_id');
    var options = select_obj.options;
    options.remove();
    options[options.length] = new Option("Loading Applications", null, false, false);
    var values = {};
    values['FUNC'] = 'getApplications';
    values['uniqid'] = uniqid;
    values['select_id'] = select_id;
    values['value'] = 'application_id';
    values['text'] = 'application_name';    
    values['return_request'] = true;
    $.ajax({data:values,success:set_select_from_json});
    return select_obj;
}

/**
 * @return HTMLSelectElement
 */
function create_or_replace_select(location_id, select_id,label_name,name_in_form){
    select_obj = $('#'+select_id);
    if(select_obj.length == 0){
        location_obj = $('#'+location_id);
        if(location_obj.length == 0){
            error('Location ID could found "'+location_id+'" ');
            return null;
        }
        $('#'+location_id).after("<label for='"+select_id+"' >"+label_name+"</label><select id='"+select_id+"' name='"+name_in_form+"'  />");
    }
    select_obj = $('#'+select_id);
    if(select_obj.length == 0){
        error("Unable to create a Select element? - contact site admin.");
        return null;
    }
    return select_obj[0];
}

function set_select_from_json(response_json){
    write_log("Setting Listbox from Server JSON "+dump(response_json.substring(0,60))+'... (cropped to 60 letters)');
    eval('response = '+response_json);
    write_log("JSON:<br>"+dump(response));
    if(!response) error('Invalid JSON ');
    if(!response.request) error('Response did not return a Request - inspect JSON ');
    if(!response.request.select_id) error('Request did not contain a select_id - inspect JSON ');
    var select_obj = $('#'+response.request.select_id);
    if(select_obj.length == 0){
        error('Invalid select_id returned from json.php = "\n'+response_json+'"');
        return;
    }
    var options = select_obj[0].options;
    if(!options){
        error("Select object - Options list not found?");
        return;
    }
    options.remove();
    if(!response.rows){
        var new_option;
        options[options.length] = new Option("Empty List", -1,false,false);
        return;
    }
    options[options.length] = new Option("<Pick One>", -1);
    $.each(response.rows,
        function() {
            options[options.length] = new Option(this[response.request.text], this[response.request.value]);
        }
    );
}



function handleResponse(obj){
     write_log("Handle response - ajaxReturned" + obj);   
    
}

function handle_user_name_change(name,event){
    var email = $(name).val();
    write_log("handle_user_name_change" + name + " event = " + event + " email = "+email);
    $.ajax({
        data: {},
        success: handleResponse
    });
}

function ajax_handle_check_user(json){
    write_log("UserName check"+json);    
}

function getHostname(str) {
	var re = new RegExp('^(?:f|ht)tp(?:s)?\://([^/]+)', 'im');
	return str.match(re)[1].toString();
}

function insert_login_box(){
  //link = $('#canvas > H1').html();
  $('#canvas > H1').after('<div class="field" id="login" ></div>'); 
  var rep_info = 'Repository Location <br/><a href="'+ajax_url+'" >'+getHostname(ajax_url)+' >';
  $('div#login').html('<table><tr ><td   align="left" >'+rep_info+'</td><td width="85%"   align="right" > <form id="login"  ><label for="user">Username/Email</label><input id="user" name="username" /></form></td></tr></table>');
  $('input#user').change(function(){
        handle_user_name_change('input#user','change');
  });
  $('input#user').keyup(function(){
  //      handle_user_name_change('input#user','Keyup');
  });
  $('form#login').append('<label for="password">Password</label><input type="password"  id="qos" name="qos" />');
  $('form#login').append('<input id="btn_login" type="button" value="Login"  /><input id="btn_new_user" type="button" value="Register"  />');
  $('div#login').css("border","silver solid 1px").css("text-align","right")
  $('div#login').css("margin","3px").css("padding","3px").css('background-color','#F8F8F8');
  // LOGIN FORM
  $("#btn_login").click(function(){
      write_log("Ajax to be called "+" '#btn_login' ");  
      var values = {};
      var myForm = $('form#login');
      write_log("Form = "+$('form#login').text() + " myForm " + myForm);
      $.each($('form#login').serializeArray(), function(i, field) {
         values[field.name] = field.value;
         write_log(" - Field " + field.name + ' has value ' +  field.value);
       });// end of each...
      //write_log("values are logged "+values.join());
      values['format']='json';
      values['FUNC']='doLogin';
      $.ajax({data:values,format:"json",FUNC:"doLogin",success:handle_login});// End Ajax Call      
    });// End Click Event
  
  $("#btn_register").click(function(){
      write_log("Ajax to be called");  
      var values = {};
      $.each($('form#login').serializeArray(), function(i, field) {
         values[field.name] = field.value;
      });
    write_log("values are logged "+values.join());
  
    $.ajax({data:values,FUNC:"doCreateUser",success:handle_login});// End Ajax Call      
    });// End Click Event
  //$('input#user').val('dummy');
  //$('input#qos').val('dummy');
  
}
/////////////////// EVENT START UP ///////////////////////
$(document).ready(function(){
   insert_login_box();    
   write_log("Ready from DbDiffRepository.js"); 
   //write_log("Found "+$(#"btn_get_from_rep1").val())
   $("#btn_get_from_rep1").click(function(event){
        load_from_repository('#div_schema_1',"#schema1","#txt_snapshot_name1");
    });
   $("#btn_get_from_rep2").click(function(event){
        key_name=$("#txt_snapshot_name2").val();
        load_from_repository('#div_schema_2',"#schema2","#txt_snapshot_name2");
    });// end of eventhandler
    checkCookie();
}); // end of Document.Ready()




